<template>
  <base-content>
    <template>
      <div v-if="!isHidden" style="text-align: right;padding-bottom: 10px;">
        <el-button type="primary" @click="handleAdd">新建优惠券</el-button>
      </div>
      <!-- 优惠券列表 -->
      <el-table key="btable" v-loading="loading" :data="couponList">
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="coupon_name" label="优惠卷名称" />
        <el-table-column prop="coupon_value" label="面值" />
        <el-table-column prop="coupon_min_consume" label="使用门槛" />
        <el-table-column label="使用范围" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.dept_name_list.join(';') }}
          </template>
        </el-table-column>
        <el-table-column prop="coupon_use_type" label="功能范围">
          <template slot-scope="scope">
            {{ scope.row.coupon_use_type === 0 ? '全部可用' : scope.row.coupon_use_type === 1 ? '仅拼团' : '仅商品' }}
          </template>
        </el-table-column>
        <el-table-column prop="is_enabled" label="状态">
          <template slot-scope="scope">
            {{ scope.row.is_enabled === 0 ? '不可用' : '可用' }}
          </template>
        </el-table-column>
        <el-table-column prop="coupon_num" label="发行量" />
        <el-table-column prop="coupon_use_num" label="使用量" />
        <el-table-column v-if="!isHidden" label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.is_enabled === 0" type="primary" size="small" @click="updateEnable(scope.row)">上架</el-button>
            <el-button v-if="scope.row.is_enabled === 1" type="primary" size="small" @click="updateEnable(scope.row)">下架</el-button>
            <el-button type="default" size="small" @click="provideCoupon(scope.row)">发放优惠券</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 控件 -->
      <el-main>
        <el-pagination background layout="prev, pager, next" :total="total" @current-change="pageChange" />
      </el-main>
      <!-- 新建优惠券 -->
      <el-dialog title="新建优惠券" :visible.sync="isShow" width="40%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="优惠卷名称">
            <el-col :span="14">
              <el-input v-model="form.coupon_name" placeholder="请输入优惠券名称" size="miedum" autocomplete="off" />
            </el-col>
          </el-form-item>
          <el-form-item label="面值">
            <el-col :span="14">
              <el-input v-model="form.coupon_value" type="number" placeholder="请输入面值" size="miedum" autocomplete="off" />
            </el-col>
          </el-form-item>
          <el-form-item label="门槛">
            <el-col :span="14">
              <el-input v-model="form.coupon_min_consume" type="number" placeholder="请输入门槛" size="miedum" autocomplete="off" />
            </el-col>
          </el-form-item>
          <el-form-item label="发行量">
            <el-col :span="14">
              <el-input v-model="form.coupon_num" type="number" placeholder="请输入发行量" size="miedum" autocomplete="off" />
            </el-col>
          </el-form-item>
          <el-form-item label="使用范围">
            <el-col :span="14">
              <!-- <wlTreeSelect v-model="form.dept_id_list" leaf checkbox :data="treeData" @change="scopeSelectChange" /> -->
              <rm-tree-select
                ref="wl-tree-select"
                v-model="form.dept_id_list"
                check-on-click-node
                node-key="id"
                width="240"
                checkbox
                no-checked-close
                :data="treeData"
                :default-expand-all="false"
                :default-expanded-keys="[1]"
                @change="scopeSelectChange"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="功能范围">
            <el-col :span="14">
              <el-select v-model="form.coupon_use_type" placeholder="请选择优惠券功能范围">
                <el-option label="全部可用" :value="0" />
                <el-option label="仅拼团" :value="1" />
                <el-option label="仅商品" :value="2" />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="状态">
            <el-col :span="14">
              <el-select v-model="form.is_enabled" placeholder="请选择优惠券使用状态">
                <el-option label="可用" :value="1" />
                <el-option label="不可用" :value="0" />
              </el-select>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submitCoupon">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 发放优惠券 -->
      <el-dialog title="发放优惠券" :visible.sync="isShowCoupon" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="优惠卷名称">{{ couponEntity.coupon_name }}</el-form-item>
          <el-form-item label="用户ID">
            <el-col :span="14">
              <el-input v-model="couponIds" type="textarea" rows="10" placeholder="请输入用户ID，每个用户ID一行" />
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submitProvideCoupon">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </base-content>
</template>

<script>
import { mapGetters } from 'vuex'
import { hasPermission } from '@/utils'
import { getCouponList, createCoupon, updateCouponStatus, sendUserCoupon } from '@/api/coupon'
import { getDeptList } from '@/api/production-api'
import RmTreeSelect from '@/components/sl-tree.vue'

export default {
  components: { RmTreeSelect },
  data() {
    return {
      // here is dialog
      isShow: false,
      isHidden: false,
      loading: false,
      isShowCoupon: false,
      couponEntity: {},
      treeData: [
        {
          id: '0',
          name: '所有平台',
          children: []
        }
      ],
      couponIds: '',
      form: {
        coupon_name: '',
        coupon_value: '',
        coupon_min_consume: '',
        coupon_use_type: '',
        is_enabled: '',
        dept_id_list: []
      },
      couponList: [],
      total: 0,
      pageNum: 1,
      pageSize: 10
    }
  },
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  },
  async created() {
    const result = await getDeptList()
    if (result.code === '0') {
      const list = result.info.data
      this.selsAreas = result.info.data
      // 初始化第一层数据
      const treeList = list.filter((item) => item.dept_parent_id === 0)
      const trees = []
      treeList.forEach((item) => {
        const arr = this.toTreeData(list, item.id)
        trees.push({ id: item.id, name: item.dept_name, children: arr })
      })
      this.treeData[0].children = trees
    } else {
      this.selsAreas = []
    }
  },
  mounted() {
    const isHidden = !hasPermission('优惠券管理')
    if (isHidden) {
      this.operations = []
      this.isHidden = isHidden
      this.baseHandles = this.baseHandles.filter((item) => item.key !== 'add')
    }
    this.query()
  },
  methods: {
    toTreeData(data, pid) {
      function tree(id) {
        const arr = []
        data.filter(item => {
          return item.dept_parent_id === id
        }).forEach(item => {
          arr.push({
            id: item.id,
            name: item.dept_name,
            children: tree(item.id)
          })
        })
        return arr
      }
      // 第一级节点的父id，是null或者0，视情况传入
      return tree(pid)
    },
    async query(param) {
      const params = {
        page_num: this.pageNum,
        page_size: this.pageSize,
        ...param
      }
      try {
        this.loading = true
        const result = await getCouponList(params)
        this.loading = false
        if (result.code === '0') {
          this.couponList = result.info.data
          this.total = result.info.meta.count
        } else {
          this.loading = false
        }
      } catch (error) {
        this.loading = false
      }
    },
    // 发放优惠券
    provideCoupon(row) {
      this.couponEntity = row
      this.isShowCoupon = true
    },
    // 确定发放优惠券
    async submitProvideCoupon() {
      const { id } = this.couponEntity
      const couponIds = this.couponIds
      if (!couponIds) {
        return this.$message.error('请输入用户ID')
      }
      const user_id_list = couponIds.split(/[\s\n]/)
      const result = await sendUserCoupon({ coupon_id: id, user_id_list })
      if (result.code === '0') {
        this.$message.success('发放优惠券成功')
        this.isShowCoupon = false
        this.couponIds = ''
        this.query()
      } else {
        this.$message.error(`发放失败：${result.msg}`)
      }
    },
    // 优惠券上下架
    async updateEnable(row) {
      const { id, is_enabled } = row
      const result = await updateCouponStatus({ coupon_id: id, is_enabled: is_enabled === 0 ? 1 : 0 })
      if (result.code === '0') {
        this.$message.success('更新成功')
        this.couponIds = ''
        this.query()
        this.close()
      } else {
        this.$message.error(`更新失败：${result.msg}`)
      }
    },
    // 可用范围 选择
    scopeSelectChange(val) {
      const scopeIds = val.map((item) => item.id)
      this.form.dept_id_list = scopeIds
    },
    // 取消创建
    close() {
      this.form = {
        coupon_name: '',
        coupon_value: '',
        coupon_min_consume: '',
        coupon_use_type: '',
        is_enabled: '',
        dept_id_list: []
      }
      this.couponIds = ''
      this.isShow = false
      this.isShowCoupon = false
    },
    // 保存优惠券
    async submitCoupon() {
      const param = this.form
      const floatValue = /^(\d+)(.\d{0,2})?$/
      if (!param.coupon_name) {
        return this.$message.error('请输入优惠券名称')
      }
      if (!param.coupon_value) {
        return this.$message.error('请输入优惠券面值')
      }
      if (!floatValue.test(param.coupon_value)) {
        return this.$message.error('优惠券面值保留两位小数')
      }
      if (!param.coupon_min_consume) {
        return this.$message.error('请输入优惠券门槛')
      }
      if (!floatValue.test(param.coupon_min_consume)) {
        return this.$message.error('优惠券门槛保留两位小数')
      }
      if (!param.coupon_num) {
        return this.$message.error('请输入优惠券发行量')
      }
      if (!/^[0-9]+$/.test(param.coupon_num)) {
        return this.$message.error('优惠券发行量只能是正整数类型')
      }
      const result = await createCoupon(param)
      if (result.code === '0') {
        this.$message.success('创建成功')
        this.close()
        this.query({ page_num: this.pageNum })
      } else {
        this.$message.error(`创建失败：${result.msg}`)
      }
    },
    // 分页事件
    pageChange(val) {
      this.pageNum = val
      this.query({ page_num: val })
    },
    handleAdd() {
      this.isShow = true
    }
  }
}
</script>
